<template>
  <div>
    <div class="main-content">
      <h3 class="club-name">
        <el-link class="club-link" type="danger" @click="navigateToClub(selectedClub.clubId)">{{ selectedClub.clubName }}</el-link>
        <link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&display=swap" rel="stylesheet">
      </h3>

      <el-divider border-style="dashed" />
      <!-- 发布社团活动部分 -->
      <el-button size="large" class="btn-launch-activities" plain @click="showEventForm = true">
        发布新活动
      </el-button>
      <el-divider border-style="dashed" />
      <el-dialog title="发布新活动" v-model="showEventForm">
        <el-form :model="eventForm" :rules="rules" ref="eventForm">
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model="eventForm.activityName"></el-input>
          </el-form-item>
          <el-form-item label="活动介绍" prop="content">
            <el-input type="textarea" v-model="eventForm.content"></el-input>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
                v-model="eventForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
                action="#"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :file-list="eventForm.fileList"
                :auto-upload="false"
                :limit="6"
                multiple
            >
              <el-button size="small" type="primary">选择文件</el-button>
              <div class="el-upload__tip">可以上传多个文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showEventForm = false">取消</el-button>
          <el-button type="primary" @click="submitEvent">提交</el-button>
        </template>
      </el-dialog>


      <!-- 审核人员加入部分 -->
      <el-text class="mx-1" type="danger">审核人员加入</el-text>
      <el-table :data="applicationList">
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="applyTime" label="申请时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="mini" type="primary" @click="approveJoinRequest(row.applicationId)">批准</el-button>
            <el-button size="mini" type="danger" @click="rejectJoinRequest(row.applicationId)">驳回</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElLoading, ElMessage, ElNotification } from 'element-plus';
import dayjs from 'dayjs';
export default {
  name: "SecondLeaderBottomRightComponent",
  props: {
    selectedClub: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      showEventForm: false,
      eventForm: {
        clubId: this.selectedClub.clubId,
        activityName: '',
        content: '',
        endTime: '',
        fileList: [],
      },
      rules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入活动介绍', trigger: 'blur' },
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
        ],
      },
      applicationList: [],
    };
  },
  created() {
    this.fetchApplicationList()
  },
  methods: {
    navigateToClub(clubId) {
      this.$router.push({ name: "ClubDetail", query: { clubId: clubId } });
    },
    handleFileChange(file, fileList) {
      this.eventForm.fileList = fileList;
    },
    handleFileRemove(file, fileList) {
      this.eventForm.fileList = fileList;
    },
    async submitEvent() {
      this.$refs.eventForm.validate(async (valid) => {
        if (valid) {
          const isLoading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          
          const formData = new FormData();
          formData.append('clubId', this.eventForm.clubId);
          formData.append('activityName', this.eventForm.activityName);
          formData.append('content', this.eventForm.content);

          // 格式化日期时间为 ISO 8601 格式
          const formattedEndTime = dayjs(this.eventForm.endTime).format('YYYY-MM-DDTHH:mm:ss');
          formData.append('endTime', formattedEndTime);

          this.eventForm.fileList.forEach(file => {
            formData.append('fileList', file.raw);
          });

          try {
            const response = await axios.post('/activity/publishActivity', formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            });

            if (response.data.code === 0) {
              ElMessage.success('活动发布成功');
              this.showEventForm = false;
              this.resetForm();
            } else {

              ElNotification({
                title: '活动发布失败',
                message: response.data.message || "未知错误",
                type: 'error',
                dangerouslyUseHTMLString: true,
              })
            }

            isLoading.close();
          } catch (error) {

            console.error('Error publishing activity:', error);
            ElMessage.error('发布活动失败，请重试');

            isLoading.close();
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    resetForm() {
      this.eventForm = {
        clubId: this.selectedClub.clubId,
        activityName: '',
        content: '',
        endTime: '',
        fileList: [],
      };
    },
    //获取申请列表
    async fetchApplicationList() {
      try {
        const response = await axios.get('/application/ApplicationList', {
          params: {
            clubId: this.selectedClub.clubId,
            getAll: false // 或者根据需求设置为 true
          }
        });
        if (response.data.code === 0) {
          console.log(response)
          this.applicationList = response.data.data;
        } else {
          ElMessage.error(response.data.message || '获取申请列表失败');
        }
      } catch (error) {
        console.error('Error fetching application list:', error);
        ElMessage.error('获取申请列表失败，请重试');
      }
    },
    async approveJoinRequest(id) {
      await this.handleApplication(id, true);
    },

    async rejectJoinRequest(id) {
      await this.handleApplication(id, false);
    },

    async handleApplication(applicationId, approve) {
      try {
        const response = await axios.post('/application/approveClub', null, {
          params: {
            applicationId: applicationId,
            approve: approve
          }
        });

        if (response.data.code === 0) {
          ElMessage.success(approve ? '申请已批准' : '申请已驳回');
          this.fetchApplicationList(); // 重新获取列表以更新数据
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        console.error('Error handling application:', error);
        ElMessage.error('操作失败，请重试');
      }
    },
  },
  mounted() {
    this.fetchApplicationList();
  },
  watch: {
    selectedClub() {
      this.fetchApplicationList();
    }
  }
};
</script>


<style scoped>
.main-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

h3.club-name {
  font-family: 'ZCOOL KuaiLe', cursive;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #d23f31;
}

.el-link.club-link {
  font-size: 28px;
  text-decoration: none;
  color: #d23f31;
  transition: all 0.3s ease;
}

.el-link.club-link:hover {
  color: #ff6b6b;
}


.btn-launch-activities {
  background-color: #ff26269e; /* 浅橙色 */
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-launch-activities:hover {
  background-color: #ff2663d5; /* 深橙色 */
}


.el-divider {
  margin: 20px 0;
}

.dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.el-dialog {
  border-radius: 10px;
}

.el-dialog__header {
  background-color: #f56c6c;
  color: white;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  background-color: #f9f9f9;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.el-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f56c6c;
  color: white;
  text-align: center;
}

.el-table td {
  text-align: center;
}

.el-select {
  width: 150px;
  border-radius: 10px;
}
.mx-1{
  font-family: 'ZCOOL KuaiLe', cursive;
  font-size: 24px;
  margin-bottom: 20px;
  text-align: center;
  color: #d23f31;
  font-weight: 300; /* 尝试降低字体粗细 */
}
</style>
